# coding=utf8

from amazon import model_drug_item
from amazon import model_drug_item_viewed


def get_items():
    last_id = None
    while True:
        res = model_drug_item.get_list(1000, last_id=last_id)
        print(res.count(True))
        if res.count(True) < 1:
            break
        for item in res:
            yield item
            # print(item['_id'])
            last_id = item['_id']


def get_bought_item(asin):
    item = model_drug_item_viewed.find_one({'Asin': asin})
    return '|'.join(item['Bought'])


if __name__ == '__main__':
    res = ['title,price,stock,ASIN,bought ASIN']
    for item in get_items():
        # 根据asin去获取购买过的物品
        res.append(
            ','.join([
                item['Title'].replace(',', '，').replace('&amp;', '&'), item['Price'].replace(',', '').replace('.', ''),
                item['StockNum'], item['ASIN'], get_bought_item(item['ASIN'])
            ])
        )
    with open("data/amazon_drug.csv", 'w', encoding='utf-8-sig') as f:
        f.write(
            '\n'.join(res)
        )
